home *** CD-ROM | disk | FTP | other *** search
/ Experimental BBS Explossion 3 / Experimental BBS Explossion III.iso / c / cp1.zip / FIGET.C < prev    next >
C/C++ Source or Header  |  1993-05-26  |  2KB  |  88 lines

  1. ===========================================================================
  2.  BBS: The Abacus * HST/DS * Potterville MI
  3. Date: 05-23-93 (19:12)             Number: 62
  4. From: BOB STOUT                    Refer#: 158
  5.   To: BRUCE BRISTOL                 Recvd: NO  
  6. Subj: Reverse Read                   Conf: (36) C Language
  7. ---------------------------------------------------------------------------
  8. In a message of <May 21 19:54>, Bruce Bristol (1:102/1006@fidonet) writes:
  9.  
  10.  >Problem: Read the last record of a flat ASCII file delimited by
  11.  >         CR/LF.
  12.  
  13.  >I'm curious if there is a function in C to read a file in reverse order.
  14.  
  15.   From SNIPPETS:
  16.  
  17. /*
  18. ** figets like fgets only works backward from filepos pos instead of
  19. ** forward from the current filepointer
  20. **
  21. ** returns fileposition of the begin of line read
  22. **
  23. ** by Jan Vroonhof
  24. */
  25.  
  26. #include <stdio.h>
  27. #include <string.h>
  28.  
  29. #define MAXLEN 90
  30.  
  31. long figets(FILE *file, char *buffer, long pos)
  32. {
  33.       char *ptr;
  34.       long aap;
  35.  
  36.       aap = (pos - MAXLEN > 0 ? pos-MAXLEN : 0L);
  37.       fseek(file, aap, SEEK_SET);
  38.       fread(buffer + 100, 1, MAXLEN, file);
  39.       buffer[pos - aap + 100] = 0;
  40.       ptr = strrchr(buffer + 100, '\n');
  41.       if (ptr)
  42.       {
  43.             *ptr = 0;
  44.             ptr = strrchr(buffer + 100, '\n');
  45.             if (ptr)
  46.             {
  47.                   strcpy(buffer, ptr + 1);
  48.                   return aap + (ptr - buffer - 100) + 1;
  49.             }
  50.             else
  51.             {
  52.                   strcpy(buffer, buffer + 100);
  53.                   return (aap ? -1L : 0L);
  54.             }
  55.       }
  56.       else
  57.       {
  58.             strcpy(buffer, buffer + 100);
  59.             return -1L;
  60.       }
  61. }
  62.  
  63. #ifdef TEST
  64.  
  65. void main(void)
  66. {
  67.       char buf[256];
  68.       FILE *fp;
  69.       long pos;
  70.  
  71.       fp = fopen("figets.c", "r");
  72.       fseek(fp, 0L, SEEK_END);
  73.       pos = ftell(fp);
  74.       do {
  75.             pos = figets(fp, buf, pos);
  76.             puts (buf);
  77.       } while (pos);
  78. }
  79.  
  80. #endif /* TEST */
  81.  
  82.  
  83. --- QM v1.00
  84.  * Origin: MicroFirm : Down to the C in chips (1:106/2000.6)
  85. SEEN-BY: 1/211 11/2 4 13/13 101/1 108/89 109/25 110/69 114/5 123/19 124/1
  86. SEEN-BY: 153/752 154/40 77 157/2 159/100 125 575 950 203/23 209/209 261/1023
  87. SEEN-BY: 280/1 390/1 396/1 5 15 2270/1 2440/5 3603/20
  88.